<?php
namespace App\Services\Core\Store\R360;
use Prophecy\Exception\Exception;

class R360Service
{
    protected $appId = 1000053;

    protected $orgPrivateKey = '-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCRMcGMrZIKu956ubKD2kDFzRtSP13ycgRtPVz+MvseTje0YgGl
ht+zGuPgCD9KgW44FFdwGS2Wp7Ir/zzEpInTPlKWjXGZP06iwlu+7p04ktgK7TB6
NjF83gHB/T//OrliHrX1l/Jzh3LFHwCAxT6fJt1Ja6eziGvxtLPT94TkcwIDAQAB
AoGAKsYYugPsUUM1cLxCLfvfNyaMlPdcCu+yBCieu7hzKGNsn7R7vbL1NgOG/FoR
ozZsLRM5CyovtwFiSPnhgiDjBSnvugLBPLKcQJX3PUb9dHOpfwXZCOg/CMwbb8fg
9bPt36oBfJYIydQjP3/9iM9t1sdtIbd/fHCL6Ry/iGcsvyECQQDA1ezZ0DlV25QX
FbL1IvufITnvcfK2KwGc4By71cWZ/tnczxGh4/YiTym7V58IR+XW326UwPdW4Mi0
xtuJagmxAkEAwMDo8VzvysfxDs0hdwxFjksZ0htPEG9FLjhp2Vu5jm+swyPBt+eW
pFvstM6YIq570y6D3Mkq2zu20F5nJnm1YwJAdxur0F3tDDs0nY2pnACfqwq63ktj
v2GQ/XTwSpUgGJ5xsxGzsms7/LUo8a6NbG/8Z1xa0Ubff6oYTpEFyTrWAQJBAJPa
phSWpH2Y1yjyYswtxqD6rKjFN+W0ZI2qyk7nlDNVKGFbaTpHU/9pX+3lVz+rNeJt
GMrgKJaYfIfjEh6qV18CQAOSaCWwd26ZE5zed045dz01Yf9zPvxYXeFm4cqK584M
Z6J84qIslgp9fhOrLv/Q4mos1CZTWzDhFbDM73NlabQ=
-----END RSA PRIVATE KEY-----';
    protected $rong360Url = 'http://openapi.rong360.com/gateway';


    public function operatorSend($bizData, $method)
    {/*{{{*/
        $params = array(
            'method' => $method,
            'app_id' => $this->appId,
            'version' => '1.0',
            'sign_type' => 'RSA',
            'format' => 'json',
            'timestamp' => time()
        );
        $params['biz_data'] = json_encode($bizData);

        $params['sign'] = $this->sign($this->getSignContent($params));
        //Yii::log('################################'.$params['sign']);

        $resp = $this->_crulPost($params, $this->rong360Url);
        return ($resp);
    }/*}}}*/

    public function tianjiSend($bizData, $method)
    {/*{{{*/
        $params = array(
            'method' => $method,
            'app_id' => $this->appId,
            'version' => '1.0',
            'sign_type' => 'RSA',
            'format' => 'json',
            'timestamp' => time()
        );
        $params['biz_data'] = json_encode($bizData);

        $params['sign'] = $this->sign($this->getSignContent($params));
        //Yii::log('################################'.$params['sign']);
        $resp = $this->_crulPost($params, $this->rong360Url);
        return ($resp);
    }/*}}}*/

    protected function getSignContent($params)
    {/*{{{*/
        ksort($params);

        $i = 0;
        $stringToBeSigned = "";
        foreach ($params as $k => $v) {
            if ($i == 0) {
                $stringToBeSigned .= "$k" . "=" . "$v";
            } else {
                $stringToBeSigned .= "&" . "$k" . "=" . "$v";
            }
            $i++;
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }/*}}}*/

    protected function sign($data)
    {/*{{{*/
        $res = $this->orgPrivateKey;
        openssl_sign($data, $sign, $res);
        $sign = base64_encode($sign);
        return $sign;
    }/*}}}*/

    private function _crulPost($postData, $url = '')
    {/*{{{*/
        if (empty($url)) {
            //Yii::log('openapi curl post数据时，目标url为空','error');
            return false;
        }

        try {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postData));
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($curl, CURLOPT_SSLVERSION, 1);
            curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($curl, CURLOPT_TIMEOUT, 30);
            $res = curl_exec($curl);

            $errno = curl_errno($curl);
            $curlInfo = curl_getinfo($curl);
            $errInfo = 'curl_err_detail: ' . curl_error($curl);
            $errInfo .= ' curlInfo:' . json_encode($curlInfo);

            $arrRet = json_decode($res, true);

            //统一记录日志
            $logLevel = 'info';
            if (!is_array($arrRet) || $arrRet['error'] != 200) {
                $logLevel = 'warning';
            }
            curl_close($curl);
        } catch (Exception $e) {
            print_r($e->getMessage());
        }

        //Yii::log("openapi curl post url: \t $url \t post: \t " . json_encode($postData) . " \t errno: $errno return: $res " . $errInfo, $logLevel);

        if ($arrRet['error'] == 0) {
            return $arrRet;
        }

        return $arrRet;
    }/*}}}*/
}
